import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AdbShell {

    /**
     * 获取PID
     *
     * @param packageName app包名
     * @return PID
     */
    public String getPID(String packageName) {
        Runtime runtime = Runtime.getRuntime();
        String pid = null;
        try {
            Process process = runtime.exec("adb shell pgrep -o " + packageName);
            if (process.waitFor() != 0) {
                System.err.println("exit value= " + process.exitValue());
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer stb = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                stb.append(line + " ");
            }
            String str = stb.toString();
            pid = str.trim();
        } catch (Exception e) {
            System.out.println(e);
        }
        return pid;
    }

    /**
     * 获取流量
     *
     * @return 上传流量+下载流量
     */
    public double getFlow(String pid) {
        double flow = 0;

        Runtime runtime = Runtime.getRuntime();
        try {
            Process proc = runtime.exec("adb shell cat /proc/" + pid + "/net/dev");
            if (proc.waitFor() != 0) {
                System.err.println("exit value = " + proc.exitValue());
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    proc.getInputStream()));
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line + " ");

            }
            String str1 = stringBuffer.toString();
            String str2 = str1.substring(str1.indexOf("wlan0:"), str1.indexOf("wlan0:") + 90);
            String str4 = str2.substring(7, 16);
            str4 = str4.trim();
            String str6 = str2.substring(67, 75);
            str6 = str6.trim();
            int b = Integer.parseInt(str4);
            int a = Integer.parseInt(str6);

            double sendFlow = a / 1024;
            double revFlow = b / 1024;
            flow = sendFlow + revFlow;
        } catch (InterruptedException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return flow;
    }

    /**
     * 获取内存
     *
     * @param PackageName
     * @return
     */
    public double getMemory(String PackageName) {

        double Heap = 0;

        return Heap;
    }
}
